<template>
	<view class="index">
		<view class="search">
			<uni-datetime-picker v-model="range" type="daterange" class="search-time" @change="change" :border="false"
				:clear-icon="false" />
		</view>
		<view class="total-price">消费总额：<span class="price">￥{{ alltPrice }}</span></view>
		<view class="list">
			<mescroll-uni @init="mescrollInit" @down="downCallback" @up="upCallback" :up='up' :fixed='false'
				:down='down'>
				<view v-for="(item,index) in pageList" :key='index'>
					<view class="order-list">
						<view class="order-title flex">
							<span>时间：{{item.orderTime}}</span>
							<span class="item-color9">{{item.dayType == 0?'早餐':item.dayType == 1?'午餐':'晚餐'}}</span>
						</view>
						<view class="item flex" v-for="child in item.orderFoodEntities" :key="child.id">
							<image :src="baseUrl+child.foodPic" mode="" class="item-img"></image>
							<view class="item-cont">
								<span class="item-weight">{{child.foodName}}</span>
								<view class="flex">
									<view class="amount">￥{{child.unitPrice}}</view>
									<view class="item-color9">x {{child.foodNumber}}</view>
								</view>
							</view>
						</view>
						<view class="flex">
							<view class="item-price">总价：<span class="amount">￥{{item.amount}}</span></view>
							<view class="cancel-order" @click="clickCancel(item)" v-if="timeOut(item.orderTime)">取消订单
							</view>
						</view>
					</view>
				</view>
			</mescroll-uni>
		</view>
		<!-- 取消订单 -->
		<u-modal v-if="cancelShow" :show="true" title="取消订单" content='请确认您是否要取消订单？' :showCancelButton="true" confirmColor="#5FC48D"
			@cancel="closecCancel" @confirm="goCancel"></u-modal>
	</view>
</template>

<script>
	import {
		cancelOrder
	} from '@/api/login.js'
	import {
		getSetInfo
	} from '@/api/home.js'
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import service from "@/common/request.js"
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				// 时间
				range: [],
				requestUrl: '/api/appletapi/listOrder',
				baseUrl: process.uniEnv.VUE_APP_API_ROOT,
				up: {
					page: {
						num: 0,
						size: 10,
						time: null
					},
					textNoMore: '到底了',
					textLoading: '正在努力加载中...',
				},
				down: {
					beforeEndDelay: 600
				},
				pageList: [],
				requestData: {
					'startDate': '',
					'endDate': '',
					'userId': this.$store.state.vuex_info.userId
				},
				requestMethod: 'GET',
				cancelShow: false,
				cancelItem: {},
				lunchEndTime: '',
				dinnerEndTime: '',
				breakfastEndTime: '',
				alltPrice: ' -- ',
			};
		},
		mounted() {
			this.getSetInfoHttp()
		},
		methods: {
			// 判断时间是否超出
			timeOut(time) {
				if (!time) return false
				let _this = this
				if (_this.tabsIndex === 0) {
					// 早餐
					// 先将time转换为日期对象
					const baseDate = new Date(time.replace(/-/g, '/'));
					// 减去一天（24小时 * 60分钟 * 60秒 * 1000毫秒）
					baseDate.setTime(baseDate.getTime() - 24 * 60 * 60 * 1000);
					// 构建前一天的日期字符串（年/月/日）
					const previousDate = `${baseDate.getFullYear()}/${baseDate.getMonth() + 1}/${baseDate.getDate()}`;
					// 比较当前时间是否早于 前一天的 breakfastEndTime
					return new Date() < new Date(`${previousDate} ${_this.breakfastEndTime.replace(/-/g, '/')}`);
				} else if (_this.tabsIndex === 1) {
					// 午餐
					return new Date() < new Date(`${time.replace(/-/g,'/')} ${_this.lunchEndTime.replace(/-/g,'/')}`)
				} else {
					// 晚餐
					return new Date() < new Date(`${time.replace(/-/g,'/')} ${_this.dinnerEndTime.replace(/-/g,'/')}`)
				}
			},
			// 取消
			clickCancel(item) {
				this.cancelItem = item
				console.log(item)
				this.cancelShow = true
			},
			closecCancel() {
				this.cancelItem = {}
				this.cancelShow = false
			},
			// 获取截止时间
			getSetInfoHttp() {
				let _this = this;
				getSetInfo().then(res => {
					if (res.success) {
						_this.breakfastEndTime = res.data.breakfastEndTime || ''
						_this.lunchEndTime = res.data.lunchEndTime
						_this.dinnerEndTime = res.data.dinnerEndTime
					}
				})
			},
			goCancel() {
				let _this = this;
				_this.cancelShow = false
				uni.showLoading({
					title: '正在取消...'
				});
				cancelOrder({
					'orderId': _this.cancelItem.id
				}).then(res => {
					uni.hideLoading();
					if (res.success) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						_this.downCallback();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}

				})
			},
			// 搜索
			change(e) {
				this.requestData.startDate = e[0]
				this.requestData.endDate = e[1]
				setTimeout(() => {
					this.downCallback()
				}, 200)
			},
			downCallback() {
				this.mescroll.resetUpScroll();
			},
			upCallback({
				num: page,
				size: limit
			}) {
				let _this = this
				const data = {
					page,
					limit,
					..._this.requestData
				}
				const method = _this.requestMethod.toLowerCase()
				service[method](_this.requestUrl, data).then(res => {
					if (res.success) {
						_this.alltPrice = _this.keepTwoDecimalStr(res.msg)
						_this.mescroll.endSuccess(res.data.length);
						if (page === 1) _this.pageList = [];
						_this.pageList = [..._this.pageList, ...res.data];
					} else {
						_this.mescroll.endBySize(0, 0);
					}

				})
			},
			//精确显示小数点后2位，没有时补0
			keepTwoDecimalStr(num) {
				const result = Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));
				let s = result.toString();
				let rs = s.indexOf('.');
				if (rs < 0) {
					rs = s.length;
					s += '.';
				}
				while (s.length <= rs + 2) {
					s += '0';
				}
				return s;
			},
		}
	};
</script>

<style lang="scss" scoped>
	page {
		height: 100%;
	}

	::v-deep.u-popup,
	.u-cell-group {
		flex: 0 !important;
	}

	.cancel-order {
		padding-right: 20rpx;
		color: #5FC48D;
		font-size: 28rpx;
	}

	.index {
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		background-color: #F8F8F8;

		.search {
			margin-bottom: 20rpx;
			height: 80rpx;
			display: flex;
			align-items: center;

			.search-time {
				width: 100%;
			}
		}

		.total-price {
			margin: 0 0 20rpx 30rpx;
			font-size: 28rpx;
			font-weight: bold;

			.price {
				color: #ff0000;
			}
		}

		.list {
			flex: 1;
			overflow: auto;
			margin-bottom: 20rpx;

			.order-list {
				margin: 0 20rpx 20rpx;
				border-radius: 10rpx;
				overflow: hidden;
				background-color: #fff;

				.order-title {
					margin: 0 20rpx;
					padding: 20rpx 0;
					font-size: 28rpx;
					border-bottom: 1px solid #F5f5f5;
				}

				.flex {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 28rpx;
				}

				.item {
					overflow: hidden;
					padding: 20rpx;
					border-bottom: 1px solid #F8F8F8;
				}

				.item:last-child {
					border-bottom: 0
				}

				.item-img {
					width: 180rpx;
					height: 140rpx;
					margin-right: 20rpx;
				}

				.item-cont {
					flex: 1;
					height: 140rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}

				.amount {
					color: #ff0000;
				}

				.item-weight {
					font-weight: bold;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}

				.item-color9 {
					color: #999;
				}

				.item-price {
					text-align: right;
					margin: 0 20rpx;
					padding: 20rpx 0;
					font-size: 28rpx;
				}
			}
		}
	}
</style>